package com.changgou.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.goods.feign.ContentFeign;
import com.changgou.content.pojo.Content;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

/**
 * @ClassName ContentDataEventListener
 * @Description 监控广告数据的改变
 * @Author 传智播客
 * @Date 13:13 2019/11/14
 * @Version 2.1
 **/
@CanalEventListener
public class ContentDataEventListener {

    @Autowired(required = false)
    private ContentFeign contentFeign;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;    // 不会对key-value序列化
//    private RedisTemplate redisTemplate;

    // @ListenPoint：可以指定监控的库和表
    @ListenPoint(destination = "example", schema = "changgou_content", table = "tb_content",
    eventType = {CanalEntry.EventType.INSERT, CanalEntry.EventType.UPDATE})
    public void contentChangeEvent(CanalEntry.EntryType entryType, CanalEntry.RowData rowData){
        // 获取到改变的数据
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        // 获取广告的分类id
        String category_id = getCategoryId(afterColumnsList, "category_id");
        // 通过分类id获取广告列表
        List<Content> list = contentFeign.findContentListByCategoryId(Long.parseLong(category_id)).getData();
        // 将数据同步到redis中
        stringRedisTemplate.boundValueOps("content_" + category_id).set(JSON.toJSONString(list));
    }

    private String getCategoryId(List<CanalEntry.Column> afterColumnsList, String category_id) {
        if (afterColumnsList != null || afterColumnsList.size() > 0){
            for (CanalEntry.Column column : afterColumnsList) {
                String columnName = column.getName();
                if (category_id.equals(columnName)){
                    return column.getValue();
                }
            }
        }
        return null;
    }

    // TODO 删除操作，将redis的数据删除掉

}
